package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.MomentsApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.VideoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class QXVideoService {

    @Reference(version = "1.0.0")
    private VideoApi videoApi;

    @Reference(version = "1.0.0")
    private MomentsApi momentsApi;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private QXMomentsService QXMomentsService;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String FREEZE_USER_REDIS_KEY_PREFIX = "FREEZE_USER";

    /**
     * 查询小视频列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult findVideoList(Integer page, Integer pageSize) {
        //获取本地线程user对象
        User user = UserThreadLocal.get();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        List<VideoVo> videoVoList = new ArrayList<>();

        PageInfo<Video> pageInfo = videoApi.findVideoList(user.getId(), page, pageSize);
        List<Video> records = pageInfo.getRecords();

        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        //通过用户ID查询所有的用户个人信息
        List<UserInfo> userInfoList = userInfoService.findUserInfoByUserIds(userIds);

        for (Video video : records) {
            VideoVo videoVo = new VideoVo();
            videoVo.setId(video.getId().toHexString());
            videoVo.setUserId(video.getUserId());
            videoVo.setCover(video.getPicUrl());//视频封面
            videoVo.setVideoUrl(video.getVideoUrl());
            videoVo.setSignature("哈哈哈哈!");//TODO
            videoVo.setLikeCount(Convert.toInt(momentsApi.findLikeCount(videoVo.getId())));//
            videoVo.setHasLiked(momentsApi.findLikeRecord(user.getId(), videoVo.getId()) ? 1 : 0);//
            videoVo.setHasFocus(videoApi.findFocusCord(user.getId(), videoVo.getUserId()) ? 1 : 0);//TODO
            videoVo.setCommentCount(Convert.toInt(momentsApi.findCommentCount(videoVo.getId())));//

            //填充用户信息
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(userInfo.getUserId(), videoVo.getUserId())) {
                    videoVo.setAvatar(userInfo.getLogo());
                    videoVo.setNickname(userInfo.getNickName());
                    break;
                }
            }
            videoVoList.add(videoVo);
        }
        pageResult.setItems(videoVoList);
        return pageResult;
    }

    /**
     * 发布小视频
     *
     * @param cover
     * @param video
     * @return
     */
    public Boolean sendVideo(MultipartFile cover, MultipartFile video) {
        //从本地线程获取用户对象
        User user = UserThreadLocal.get();
        Video vid = new Video();
        vid.setUserId(user.getId());
        vid.setSeeType(1);//默认公开可见
        try {
            //上传封面图片至阿里云
            PicUploadResult uploadResult = picUploadService.upload(cover);
            vid.setPicUrl(uploadResult.getName());//保存图片路径
            //上传视频至fastdfs
            StorePath storePath = fastFileStorageClient.uploadFile(video.getInputStream(),//文件字节输入流
                    video.getSize(),//文件大小
                    StrUtil.subAfter(video.getOriginalFilename(), '.', true),//获取文件后缀名
                    null);
            //设置视频url
            vid.setVideoUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());
            //将video对象保存至本地
            String videoId = videoApi.saveVideo(vid);
            return StrUtil.isNotEmpty(videoId);
        } catch (IOException e) {
            log.error("发布小视频失败！file = " + cover.getOriginalFilename(), e);
        }
        return false;
    }

    /**
     * 小视频评论列表
     *
     * @param videoId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult findCommentList(String videoId, Integer page, Integer pageSize) {
        return QXMomentsService.findCommentList(videoId, page, pageSize);
    }

    /**
     * 小视频评论
     *
     * @param videoId
     * @param comment
     * @return
     */
    public Boolean sendComment(String videoId, String comment) {

        return QXMomentsService.sendComment(videoId, comment);
    }

    /**
     * 小视频点赞
     * 小视频的点赞与取消点赞和之前所做的动态的点赞取消点赞实际是完全一样的逻辑,所以直接调用圈子中的方法即可
     *
     * @param videoId
     * @return
     */
    public Long likeVideo(String videoId) {
        User user = UserThreadLocal.get();
        Boolean result = momentsApi.likeComment(user.getId(), videoId);
        if (result) {
            return momentsApi.findLikeCount(videoId);
        }
        return null;
    }

    /**
     * 小视频取消点赞
     * 小视频的点赞与取消点赞和之前所做的动态的点赞取消点赞实际是完全一样的逻辑,所以直接调用圈子中的方法即可
     *
     * @param videoId
     * @return
     */
    public Long disLikeVideo(String videoId) {
        User user = UserThreadLocal.get();
        Boolean result = momentsApi.disLikeComment(user.getId(), videoId);
        if (result) {
            return momentsApi.findLikeCount(videoId);
        }
        return null;
    }

    /**
     * 关注小视频
     *
     * @param userId 被关注的这条视频的发布者的ID
     * @return
     */
    public Boolean focusVideo(Long userId) {
        User user = UserThreadLocal.get();
        return videoApi.focusVideo(user.getId(), userId);
    }

    /**
     * 取消关注小视频
     *
     * @param userId
     * @return
     */
    public Boolean unFocusVideo(Long userId) {
        User user = UserThreadLocal.get();
        return videoApi.unFocusVideo(user.getId(), userId);
    }

    private String getFreezeUserRedisKeyPrefix(Integer uid) {
        return FREEZE_USER_REDIS_KEY_PREFIX + uid;
    }
}
